package kuang;

/**
 * @author cyt
 * @create 2020-03-08 21:40
 */

/**
 * 模拟消费者， 生产者问题
 * 消费者， 生产者， 缓冲器， 产品。
 */
public class Thread_Process {

    public static void main(String[] args) {
        Container container = new Container();
        new Provide(container).start();
        new Customer(container).start();
    }
}

class Provide extends Thread {
    Container container;

    public Provide(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                container.push(new Chicken(i));
                System.out.println("生产了" + i + "只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Customer extends Thread {
    Container container;

    public Customer(Container container) {
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Chicken pop = null;
            try {
                Chicken chicken = container.pop();
                System.out.println("消费了第几只：" + chicken.id);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

class Chicken {
    int id;

    public Chicken(int id) {
        this.id = id;
    }
}

class Container {
    Chicken[] chickens = new Chicken[10];

    int count = 0;

    // 生产者
    public synchronized void push(Chicken chicken) throws InterruptedException {
        // 满了 就等待消费
        if (count == chickens.length) {
            // 通知消费者， 消费
            this.wait();
        }

        //未满， 就生产
        chickens[count] = chicken;
        count++;

        this.notify();

    }

    // 消费者
    public synchronized Chicken pop() throws InterruptedException {
        // 满了 就等待消费
        if (count == 0) {
            // 通知消费者， 消费
            this.wait();
        }
        count--;
        Chicken c = chickens[count];
        this.notify();
        return c;
    }
}
